home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / usenet / sources / volume89 / editors / stevie3a.5 < prev    next >
Text File  |  1989-03-15  |  54KB  |  2,368 lines

  1. Path: xanth!ukma!mailrus!ulowell!page
  2. From: page@swan.ulowell.edu (Bob Page)
  3. Newsgroups: comp.sources.amiga
  4. Subject: v89i044:  stevie - vi-like text editor v35a, Part05/06
  5. Message-ID: <12217@swan.ulowell.edu>
  6. Date: 15 Mar 89 15:12:50 GMT
  7. Organization: University of Lowell, Computer Science Dept.
  8. Lines: 2357
  9. Approved: page@swan.ulowell.edu
  10.  
  11. Submitted-by: grwalter@watcgl.waterloo.edu (Fred Walter)
  12. Posting-number: Volume 89, Issue 44
  13. Archive-name: editors/stevie35a.5
  14.  
  15. #    This is a shell archive.
  16. #    Remove everything above and including the cut line.
  17. #    Then run the rest of the file through sh.
  18. #----cut here-----cut here-----cut here-----cut here----#
  19. #!/bin/sh
  20. # shar:    Shell Archiver
  21. #    Run the following text with /bin/sh to create:
  22. #    regexp.c
  23. #    search.c
  24. # This archive created: Tue Mar 14 14:42:24 1989
  25. cat << \SHAR_EOF > regexp.c
  26. /*
  27.  * NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
  28.  *
  29.  * This is NOT the original regular expression code as written by
  30.  * Henry Spencer. This code has been modified specifically for use
  31.  * with the STEVIE editor, and should not be used apart from compiling
  32.  * STEVIE. If you want a good regular expression library, get the
  33.  * original code. The copyright notice that follows is from the
  34.  * original.
  35.  *
  36.  * NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
  37.  *
  38.  *
  39.  * regcomp and regexec -- regsub and regerror are elsewhere
  40.  *
  41.  *    Copyright (c) 1986 by University of Toronto.
  42.  *    Written by Henry Spencer.  Not derived from licensed software.
  43.  *
  44.  *    Permission is granted to anyone to use this software for any
  45.  *    purpose on any computer system, and to redistribute it freely,
  46.  *    subject to the following restrictions:
  47.  *
  48.  *    1. The author is not responsible for the consequences of use of
  49.  *        this software, no matter how awful, even if they arise
  50.  *        from defects in it.
  51.  *
  52.  *    2. The origin of this software must not be misrepresented, either
  53.  *        by explicit claim or by omission.
  54.  *
  55.  *    3. Altered versions must be plainly marked as such, and must not
  56.  *        be misrepresented as being the original software.
  57.  *
  58.  * Beware that some of this code is subtly aware of the way operator
  59.  * precedence is structured in regular expressions.  Serious changes in
  60.  * regular-expression syntax might require a total rethink.
  61.  *
  62.  * $Log:    regexp.c,v $
  63.  * Revision 1.2  88/04/28  08:09:45  tony
  64.  * First modification of the regexp library. Added an external variable
  65.  * 'reg_ic' which can be set to indicate that case should be ignored.
  66.  * Added a new parameter to regexec() to indicate that the given string
  67.  * comes from the beginning of a line and is thus eligible to match
  68.  * 'beginning-of-line'.
  69.  * 
  70.  */
  71. #include "env.h"
  72.  
  73. #ifdef    MEGAMAX
  74. overlay "regexp"
  75. #endif
  76.  
  77. #include <stdio.h>
  78. #include "regexp.h"
  79. #include "regmagic.h"
  80.  
  81. /*
  82.  * The "internal use only" fields in regexp.h are present to pass info from
  83.  * compile to execute that permits the execute phase to run lots faster on
  84.  * simple cases.  They are:
  85.  *
  86.  * regstart    char that must begin a match; '\0' if none obvious
  87.  * reganch    is the match anchored (at beginning-of-line only)?
  88.  * regmust    string (pointer into program) that match must include, or NULL
  89.  * regmlen    length of regmust string
  90.  *
  91.  * Regstart and reganch permit very fast decisions on suitable starting points
  92.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  93.  * of lines that cannot possibly match.  The regmust tests are costly enough
  94.  * that regcomp() supplies a regmust only if the r.e. contains something
  95.  * potentially expensive (at present, the only such thing detected is * or +
  96.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  97.  * supplied because the test in regexec() needs it and regcomp() is computing
  98.  * it anyway.
  99.  */
  100.  
  101. /*
  102.  * Structure for regexp "program".  This is essentially a linear encoding
  103.  * of a nondeterministic finite-state machine (aka syntax charts or
  104.  * "railroad normal form" in parsing technology).  Each node is an opcode
  105.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  106.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  107.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  108.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  109.  * opposed to a collection of them) is never concatenated with anything
  110.  * because of operator precedence.)  The operand of some types of node is
  111.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  112.  * particular, the operand of a BRANCH node is the first node of the branch.
  113.  * (NB this is *not* a tree structure:  the tail of the branch connects
  114.  * to the thing following the set of BRANCHes.)  The opcodes are:
  115.  */
  116.  
  117. /* definition    number    opnd?    meaning */
  118. #define    END    0        /* no    End of program. */
  119. #define    BOL    1        /* no    Match "" at beginning of line. */
  120. #define    EOL    2        /* no    Match "" at end of line. */
  121. #define    ANY    3        /* no    Match any one character. */
  122. #define    ANYOF    4        /* str    Match any character in this string. */
  123. #define    ANYBUT    5        /* str    Match any character not in this
  124.                  * string. */
  125. #define    BRANCH    6        /* node    Match this alternative, or the
  126.                  * next... */
  127. #define    BACK    7        /* no    Match "", "next" ptr points backward. */
  128. #define    EXACTLY    8        /* str    Match this string. */
  129. #define    NOTHING    9        /* no    Match empty string. */
  130. #define    STAR    10        /* node    Match this (simple) thing 0 or more
  131.                  * times. */
  132. #define    PLUS    11        /* node    Match this (simple) thing 1 or more
  133.                  * times. */
  134. #define    OPEN    20        /* no    Mark this point in input as start of
  135.                  * #n. */
  136.  /* OPEN+1 is number 1, etc. */
  137. #define    CLOSE    30        /* no    Analogous to OPEN. */
  138.  
  139. /*
  140.  * Opcode notes:
  141.  *
  142.  * BRANCH    The set of branches constituting a single choice are hooked
  143.  *        together with their "next" pointers, since precedence prevents
  144.  *        anything being concatenated to any individual branch.  The
  145.  *        "next" pointer of the last BRANCH in a choice points to the
  146.  *        thing following the whole choice.  This is also where the
  147.  *        final "next" pointer of each individual branch points; each
  148.  *        branch starts with the operand node of a BRANCH node.
  149.  *
  150.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  151.  *        exists to make loop structures possible.
  152.  *
  153.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  154.  *        BRANCH structures using BACK.  Simple cases (one character
  155.  *        per match) are implemented with STAR and PLUS for speed
  156.  *        and to minimize recursive plunges.
  157.  *
  158.  * OPEN,CLOSE    ...are numbered at compile time.
  159.  */
  160.  
  161. /*
  162.  * A node is one char of opcode followed by two chars of "next" pointer.
  163.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  164.  * value is a positive offset from the opcode of the node containing it.
  165.  * An operand, if any, simply follows the node.  (Note that much of the
  166.  * code generation knows about this implicit relationship.)
  167.  *
  168.  * Using two bytes for the "next" pointer is vast overkill for most things,
  169.  * but allows patterns to get big without disasters.
  170.  */
  171. #define    OP(p)    (*(p))
  172. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  173. #define    OPERAND(p)    ((p) + 3)
  174.  
  175. /*
  176.  * See regmagic.h for one further detail of program structure.
  177.  */
  178.  
  179.  
  180. /*
  181.  * Utility definitions.
  182.  */
  183. #ifndef CHARBITS
  184. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  185. #else
  186. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  187. #endif
  188.  
  189. #define    FAIL(m)    { regerror(m); return(NULL); }
  190. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  191. #define    META    "^$.[()|?+*\\"
  192.  
  193. /*
  194.  * Flags to be passed up and down.
  195.  */
  196. #define    HASWIDTH    01    /* Known never to match null string. */
  197. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  198. #define    SPSTART        04    /* Starts with * or +. */
  199. #define    WORST        0    /* Worst case. */
  200.  
  201. #ifndef    ORIGINAL
  202. /*
  203.  * The following supports the ability to ignore case in searches.
  204.  */
  205.  
  206. #include <ctype.h>
  207.  
  208. int             reg_ic = 0;    /* set by callers to ignore case */
  209.  
  210. /*
  211.  * mkup - convert to upper case IF we're doing caseless compares
  212.  */
  213. #define    mkup(c)        ((islower(c) && reg_ic) ? toupper(c) : (c))
  214.  
  215. #endif
  216.  
  217. /*
  218.  * Global work variables for regcomp().
  219.  */
  220. static char    *regparse;    /* Input-scan pointer. */
  221. static int      regnpar;    /* () count. */
  222. static char     regdummy;
  223. static char    *regcode;    /* Code-emit pointer; ®dummy = don't. */
  224. static long     regsize;    /* Code size. */
  225.  
  226. /*
  227.  * Forward declarations for regcomp()'s friends.
  228.  */
  229. #ifndef STATIC
  230. #define    STATIC    static
  231. #endif
  232. STATIC char    *reg();
  233. STATIC char    *regbranch();
  234. STATIC char    *regpiece();
  235. STATIC char    *regatom();
  236. STATIC char    *regnode();
  237. STATIC char    *regnext();
  238. STATIC void     regc();
  239. STATIC void     reginsert();
  240. STATIC void     regtail();
  241. STATIC void     regoptail();
  242. #ifdef STRCSPN
  243. STATIC int      strcspn();
  244. #endif
  245.  
  246. /*
  247.  - regcomp - compile a regular expression into internal code
  248.  *
  249.  * We can't allocate space until we know how big the compiled form will be,
  250.  * but we can't compile it (and thus know how big it is) until we've got a
  251.  * place to put the code.  So we cheat:  we compile it twice, once with code
  252.  * generation turned off and size counting turned on, and once "for real".
  253.  * This also means that we don't allocate space until we are sure that the
  254.  * thing really will compile successfully, and we never have to move the
  255.  * code and thus invalidate pointers into it.  (Note that it has to be in
  256.  * one piece because free() must be able to free it all.)
  257.  *
  258.  * Beware that the optimization-preparation code in here knows about some
  259.  * of the structure of the compiled regexp.
  260.  */
  261. regexp         *
  262. regcomp(exp)
  263.     char           *exp;
  264. {
  265.     register regexp *r;
  266.     register char  *scan;
  267.     register char  *longest;
  268.     register int    len;
  269.     int             flags;
  270. /*  extern char    *malloc();*/
  271.     extern char    *alloc();
  272.  
  273.     if (exp == NULL)
  274.     FAIL("NULL argument");
  275.  
  276.     /* First pass: determine size, legality. */
  277.     regparse = exp;
  278.     regnpar = 1;
  279.     regsize = 0L;
  280.     regcode = ®dummy;
  281.     regc(MAGIC);
  282.     if (reg(0, &flags) == NULL)
  283.     return (NULL);
  284.  
  285.     /* Small enough for pointer-storage convention? */
  286.     if (regsize >= 32767L)    /* Probably could be 65535L. */
  287.     FAIL("regexp too big");
  288.  
  289.     /* Allocate space. */
  290. /*  r = (regexp *) malloc((unsigned) (sizeof(regexp) + regsize));*/
  291.     r = (regexp *) alloc((unsigned) (sizeof(regexp) + regsize));
  292.     if (r == NULL)
  293.     FAIL("out of space");
  294.  
  295.     /* Second pass: emit code. */
  296.     regparse = exp;
  297.     regnpar = 1;
  298.     regcode = r->program;
  299.     regc(MAGIC);
  300.     if (reg(0, &flags) == NULL)
  301.     return (NULL);
  302.  
  303.     /* Dig out information for optimizations. */
  304.     r->regstart = '\0';        /* Worst-case defaults. */
  305.     r->reganch = 0;
  306.     r->regmust = NULL;
  307.     r->regmlen = 0;
  308.     scan = r->program + 1;    /* First BRANCH. */
  309.     if (OP(regnext(scan)) == END) {    /* Only one top-level choice. */
  310.     scan = OPERAND(scan);
  311.  
  312.     /* Starting-point info. */
  313.     if (OP(scan) == EXACTLY)
  314.         r->regstart = *OPERAND(scan);
  315.     else if (OP(scan) == BOL)
  316.         r->reganch++;
  317.  
  318.     /*
  319.      * If there's something expensive in the r.e., find the longest
  320.      * literal string that must appear and make it the regmust.  Resolve
  321.      * ties in favor of later strings, since the regstart check works
  322.      * with the beginning of the r.e. and avoiding duplication
  323.      * strengthens checking.  Not a strong reason, but sufficient in the
  324.      * absence of others. 
  325.      */
  326.     if (flags & SPSTART) {
  327.         longest = NULL;
  328.         len = 0;
  329.         for (; scan != NULL; scan = regnext(scan))
  330.         if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  331.             longest = OPERAND(scan);
  332.             len = strlen(OPERAND(scan));
  333.         }
  334.         r->regmust = longest;
  335.         r->regmlen = len;
  336.     }
  337.     }
  338.     return (r);
  339. }
  340.  
  341. /*
  342.  - reg - regular expression, i.e. main body or parenthesized thing
  343.  *
  344.  * Caller must absorb opening parenthesis.
  345.  *
  346.  * Combining parenthesis handling with the base level of regular expression
  347.  * is a trifle forced, but the need to tie the tails of the branches to what
  348.  * follows makes it hard to avoid.
  349.  */
  350. static char    *
  351. reg(paren, flagp)
  352.     int             paren;    /* Parenthesized? */
  353.     int            *flagp;
  354. {
  355.     register char  *ret;
  356.     register char  *br;
  357.     register char  *ender;
  358.     register int    parno;
  359.     int             flags;
  360.  
  361.     *flagp = HASWIDTH;        /* Tentatively. */
  362.  
  363.     /* Make an OPEN node, if parenthesized. */
  364.     if (paren) {
  365.     if (regnpar >= NSUBEXP)
  366.         FAIL("too many ()");
  367.     parno = regnpar;
  368.     regnpar++;
  369.     ret = regnode(OPEN + parno);
  370.     } else
  371.     ret = NULL;
  372.  
  373.     /* Pick up the branches, linking them together. */
  374.     br = regbranch(&flags);
  375.     if (br == NULL)
  376.     return (NULL);
  377.     if (ret != NULL)
  378.     regtail(ret, br);    /* OPEN -> first. */
  379.     else
  380.     ret = br;
  381.     if (!(flags & HASWIDTH))
  382.     *flagp &= ~HASWIDTH;
  383.     *flagp |= flags & SPSTART;
  384.     while (*regparse == '|') {
  385.     regparse++;
  386.     br = regbranch(&flags);
  387.     if (br == NULL)
  388.         return (NULL);
  389.     regtail(ret, br);    /* BRANCH -> BRANCH. */
  390.     if (!(flags & HASWIDTH))
  391.         *flagp &= ~HASWIDTH;
  392.     *flagp |= flags & SPSTART;
  393.     }
  394.  
  395.     /* Make a closing node, and hook it on the end. */
  396.     ender = regnode((paren) ? CLOSE + parno : END);
  397.     regtail(ret, ender);
  398.  
  399.     /* Hook the tails of the branches to the closing node. */
  400.     for (br = ret; br != NULL; br = regnext(br))
  401.     regoptail(br, ender);
  402.  
  403.     /* Check for proper termination. */
  404.     if (paren && *regparse++ != ')') {
  405.     FAIL("unmatched ()");
  406.     } else if (!paren && *regparse != '\0') {
  407.     if (*regparse == ')') {
  408.         FAIL("unmatched ()");
  409.     } else
  410.         FAIL("junk on end");/* "Can't happen". */
  411.     /* NOTREACHED */
  412.     }
  413.     return (ret);
  414. }
  415.  
  416. /*
  417.  - regbranch - one alternative of an | operator
  418.  *
  419.  * Implements the concatenation operator.
  420.  */
  421. static char    *
  422. regbranch(flagp)
  423.     int            *flagp;
  424. {
  425.     register char  *ret;
  426.     register char  *chain;
  427.     register char  *latest;
  428.     int             flags;
  429.  
  430.     *flagp = WORST;        /* Tentatively. */
  431.  
  432.     ret = regnode(BRANCH);
  433.     chain = NULL;
  434.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  435.     latest = regpiece(&flags);
  436.     if (latest == NULL)
  437.         return (NULL);
  438.     *flagp |= flags & HASWIDTH;
  439.     if (chain == NULL)    /* First piece. */
  440.         *flagp |= flags & SPSTART;
  441.     else
  442.         regtail(chain, latest);
  443.     chain = latest;
  444.     }
  445.     if (chain == NULL)        /* Loop ran zero times. */
  446.     (void) regnode(NOTHING);
  447.  
  448.     return (ret);
  449. }
  450.  
  451. /*
  452.  - regpiece - something followed by possible [*+?]
  453.  *
  454.  * Note that the branching code sequences used for ? and the general cases
  455.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  456.  * both the endmarker for their branch list and the body of the last branch.
  457.  * It might seem that this node could be dispensed with entirely, but the
  458.  * endmarker role is not redundant.
  459.  */
  460. static char    *
  461. regpiece(flagp)
  462.     int            *flagp;
  463. {
  464.     register char  *ret;
  465.     register char   op;
  466.     register char  *next;
  467.     int             flags;
  468.  
  469.     ret = regatom(&flags);
  470.     if (ret == NULL)
  471.     return (NULL);
  472.  
  473.     op = *regparse;
  474.     if (!ISMULT(op)) {
  475.     *flagp = flags;
  476.     return (ret);
  477.     }
  478.     if (!(flags & HASWIDTH) && op != '?')
  479.     FAIL("*+ operand could be empty");
  480.     *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
  481.  
  482.     if (op == '*' && (flags & SIMPLE))
  483.     reginsert(STAR, ret);
  484.     else if (op == '*') {
  485.     /* Emit x* as (x&|), where & means "self". */
  486.     reginsert(BRANCH, ret);    /* Either x */
  487.     regoptail(ret, regnode(BACK));    /* and loop */
  488.     regoptail(ret, ret);    /* back */
  489.     regtail(ret, regnode(BRANCH));    /* or */
  490.     regtail(ret, regnode(NOTHING));    /* null. */
  491.     } else if (op == '+' && (flags & SIMPLE))
  492.     reginsert(PLUS, ret);
  493.     else if (op == '+') {
  494.     /* Emit x+ as x(&|), where & means "self". */
  495.     next = regnode(BRANCH);    /* Either */
  496.     regtail(ret, next);
  497.     regtail(regnode(BACK), ret);    /* loop back */
  498.     regtail(next, regnode(BRANCH));    /* or */
  499.     regtail(ret, regnode(NOTHING));    /* null. */
  500.     } else if (op == '?') {
  501.     /* Emit x? as (x|) */
  502.     reginsert(BRANCH, ret);    /* Either x */
  503.     regtail(ret, regnode(BRANCH));    /* or */
  504.     next = regnode(NOTHING);/* null. */
  505.     regtail(ret, next);
  506.     regoptail(ret, next);
  507.     }
  508.     regparse++;
  509.     if (ISMULT(*regparse))
  510.     FAIL("nested *?+");
  511.  
  512.     return (ret);
  513. }
  514.  
  515. /*
  516.  - regatom - the lowest level
  517.  *
  518.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  519.  * it can turn them into a single node, which is smaller to store and
  520.  * faster to run.  Backslashed characters are exceptions, each becoming a
  521.  * separate node; the code is simpler that way and it's not worth fixing.
  522.  */
  523. static char    *
  524. regatom(flagp)
  525.     int            *flagp;
  526. {
  527.     register char  *ret;
  528.     int             flags;
  529.  
  530.     *flagp = WORST;        /* Tentatively. */
  531.  
  532.     switch (*regparse++) {
  533.       case '^':
  534.     ret = regnode(BOL);
  535.     break;
  536.       case '$':
  537.     ret = regnode(EOL);
  538.     break;
  539.       case '.':
  540.     ret = regnode(ANY);
  541.     *flagp |= HASWIDTH | SIMPLE;
  542.     break;
  543.       case '[':{
  544.         register int    class;
  545.         register int    classend;
  546.  
  547.         if (*regparse == '^') {    /* Complement of range. */
  548.         ret = regnode(ANYBUT);
  549.         regparse++;
  550.         } else
  551.         ret = regnode(ANYOF);
  552.         if (*regparse == ']' || *regparse == '-')
  553.         regc(*regparse++);
  554.         while (*regparse != '\0' && *regparse != ']') {
  555.         if (*regparse == '-') {
  556.             regparse++;
  557.             if (*regparse == ']' || *regparse == '\0')
  558.             regc('-');
  559.             else {
  560.             class = UCHARAT(regparse - 2) + 1;
  561.             classend = UCHARAT(regparse);
  562.             if (class > classend + 1)
  563.                 FAIL("invalid [] range");
  564.             for (; class <= classend; class++)
  565.                 regc(class);
  566.             regparse++;
  567.             }
  568.         } else
  569.             regc(*regparse++);
  570.         }
  571.         regc('\0');
  572.         if (*regparse != ']')
  573.         FAIL("unmatched []");
  574.         regparse++;
  575.         *flagp |= HASWIDTH | SIMPLE;
  576.     }
  577.     break;
  578.       case '(':
  579.     ret = reg(1, &flags);
  580.     if (ret == NULL)
  581.         return (NULL);
  582.     *flagp |= flags & (HASWIDTH | SPSTART);
  583.     break;
  584.       case '\0':
  585.       case '|':
  586.       case ')':
  587.     FAIL("internal urp");    /* Supposed to be caught earlier. */
  588.     /* break; Not Reached */
  589.       case '?':
  590.       case '+':
  591.       case '*':
  592.     FAIL("?+* follows nothing");
  593.     /* break; Not Reached */
  594.       case '\\':
  595.     if (*regparse == '\0')
  596.         FAIL("trailing \\");
  597.     ret = regnode(EXACTLY);
  598.     regc(*regparse++);
  599.     regc('\0');
  600.     *flagp |= HASWIDTH | SIMPLE;
  601.     break;
  602.       default:{
  603.         register int    len;
  604.         register char   ender;
  605.  
  606.         regparse--;
  607.         len = strcspn(regparse, META);
  608.         if (len <= 0)
  609.         FAIL("internal disaster");
  610.         ender = *(regparse + len);
  611.         if (len > 1 && ISMULT(ender))
  612.         len--;        /* Back off clear of ?+* operand. */
  613.         *flagp |= HASWIDTH;
  614.         if (len == 1)
  615.         *flagp |= SIMPLE;
  616.         ret = regnode(EXACTLY);
  617.         while (len > 0) {
  618.         regc(*regparse++);
  619.         len--;
  620.         }
  621.         regc('\0');
  622.     }
  623.     break;
  624.     }
  625.  
  626.     return (ret);
  627. }
  628.  
  629. /*
  630.  - regnode - emit a node
  631.  */
  632. static char    *        /* Location. */
  633. regnode(op)
  634.     char            op;
  635. {
  636.     register char  *ret;
  637.     register char  *ptr;
  638.  
  639.     ret = regcode;
  640.     if (ret == ®dummy) {
  641.     regsize += 3;
  642.     return (ret);
  643.     }
  644.     ptr = ret;
  645.     *ptr++ = op;
  646.     *ptr++ = '\0';        /* Null "next" pointer. */
  647.     *ptr++ = '\0';
  648.     regcode = ptr;
  649.  
  650.     return (ret);
  651. }
  652.  
  653. /*
  654.  - regc - emit (if appropriate) a byte of code
  655.  */
  656. static void
  657. regc(b)
  658.     char            b;
  659. {
  660.     if (regcode != ®dummy)
  661.     *regcode++ = b;
  662.     else
  663.     regsize++;
  664. }
  665.  
  666. /*
  667.  - reginsert - insert an operator in front of already-emitted operand
  668.  *
  669.  * Means relocating the operand.
  670.  */
  671. static void
  672. reginsert(op, opnd)
  673.     char            op;
  674.     char           *opnd;
  675. {
  676.     register char  *src;
  677.     register char  *dst;
  678.     register char  *place;
  679.  
  680.     if (regcode == ®dummy) {
  681.     regsize += 3;
  682.     return;
  683.     }
  684.     src = regcode;
  685.     regcode += 3;
  686.     dst = regcode;
  687.     while (src > opnd)
  688.     *--dst = *--src;
  689.  
  690.     place = opnd;        /* Op node, where operand used to be. */
  691.     *place++ = op;
  692.     *place++ = '\0';
  693.     *place++ = '\0';
  694. }
  695.  
  696. /*
  697.  - regtail - set the next-pointer at the end of a node chain
  698.  */
  699. static void
  700. regtail(p, val)
  701.     char           *p;
  702.     char           *val;
  703. {
  704.     register char  *scan;
  705.     register char  *temp;
  706.     register int    offset;
  707.  
  708.     if (p == ®dummy)
  709.     return;
  710.  
  711.     /* Find last node. */
  712.     scan = p;
  713.     for (;;) {
  714.     temp = regnext(scan);
  715.     if (temp == NULL)
  716.         break;
  717.     scan = temp;
  718.     }
  719.  
  720.     if (OP(scan) == BACK)
  721.     offset = scan - val;
  722.     else
  723.     offset = val - scan;
  724.     *(scan + 1) = (char) ((offset >> 8) & 0377);
  725.     *(scan + 2) = (char) (offset & 0377);
  726. }
  727.  
  728. /*
  729.  - regoptail - regtail on operand of first argument; nop if operandless
  730.  */
  731. static void
  732. regoptail(p, val)
  733.     char           *p;
  734.     char           *val;
  735. {
  736.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  737.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  738.     return;
  739.     regtail(OPERAND(p), val);
  740. }
  741.  
  742. /*
  743.  * regexec and friends
  744.  */
  745.  
  746. /*
  747.  * Global work variables for regexec().
  748.  */
  749. static char    *reginput;    /* String-input pointer. */
  750. static char    *regbol;        /* Beginning of input, for ^ check. */
  751. static char   **regstartp;    /* Pointer to startp array. */
  752. static char   **regendp;    /* Ditto for endp. */
  753.  
  754. /*
  755.  * Forwards.
  756.  */
  757. STATIC int      regtry();
  758. STATIC int      regmatch();
  759. STATIC int      regrepeat();
  760.  
  761. #ifdef DEBUG
  762. int             regnarrate = 0;
  763. void            regdump();
  764. STATIC char    *regprop();
  765. #endif
  766.  
  767. /*
  768.  - regexec - match a regexp against a string
  769.  */
  770. int
  771. regexec(prog, string, at_bol)
  772.     register regexp *prog;
  773.     register char  *string;
  774.     int             at_bol;
  775. {
  776.     register char  *s;
  777.     extern char    *cstrchr();
  778.  
  779.     /* Be paranoid... */
  780.     if (prog == NULL || string == NULL) {
  781.     regerror("NULL parameter");
  782.     return (0);
  783.     }
  784.     /* Check validity of program. */
  785.     if (UCHARAT(prog->program) != MAGIC) {
  786.     regerror("corrupted program");
  787.     return (0);
  788.     }
  789.     /* If there is a "must appear" string, look for it. */
  790.     if (prog->regmust != NULL) {
  791.     s = string;
  792.     while ((s = cstrchr(s, prog->regmust[0])) != NULL) {
  793.         if (cstrncmp(s, prog->regmust, prog->regmlen) == 0)
  794.         break;        /* Found it. */
  795.         s++;
  796.     }
  797.     if (s == NULL)        /* Not present. */
  798.         return (0);
  799.     }
  800.     /* Mark beginning of line for ^ . */
  801.     if (at_bol)
  802.     regbol = string;    /* is possible to match bol */
  803.     else
  804.     regbol = NULL;        /* we aren't there, so don't match it */
  805.  
  806.     /* Simplest case:  anchored match need be tried only once. */
  807.     if (prog->reganch)
  808.     return (regtry(prog, string));
  809.  
  810.     /* Messy cases:  unanchored match. */
  811.     s = string;
  812.     if (prog->regstart != '\0')
  813.     /* We know what char it must start with. */
  814.     while ((s = cstrchr(s, prog->regstart)) != NULL) {
  815.         if (regtry(prog, s))
  816.         return (1);
  817.         s++;
  818.     }
  819.     else
  820.     /* We don't -- general case. */
  821.     do {
  822.         if (regtry(prog, s))
  823.         return (1);
  824.     } while (*s++ != '\0');
  825.  
  826.     /* Failure. */
  827.     return (0);
  828. }
  829.  
  830. /*
  831.  - regtry - try match at specific point
  832.  */
  833. static int            /* 0 failure, 1 success */
  834. regtry(prog, string)
  835.     regexp         *prog;
  836.     char           *string;
  837. {
  838.     register int    i;
  839.     register char **sp;
  840.     register char **ep;
  841.  
  842.     reginput = string;
  843.     regstartp = prog->startp;
  844.     regendp = prog->endp;
  845.  
  846.     sp = prog->startp;
  847.     ep = prog->endp;
  848.     for (i = NSUBEXP; i > 0; i--) {
  849.     *sp++ = NULL;
  850.     *ep++ = NULL;
  851.     }
  852.     if (regmatch(prog->program + 1)) {
  853.     prog->startp[0] = string;
  854.     prog->endp[0] = reginput;
  855.     return (1);
  856.     } else
  857.     return (0);
  858. }
  859.  
  860. /*
  861.  - regmatch - main matching routine
  862.  *
  863.  * Conceptually the strategy is simple:  check to see whether the current
  864.  * node matches, call self recursively to see whether the rest matches,
  865.  * and then act accordingly.  In practice we make some effort to avoid
  866.  * recursion, in particular by going through "ordinary" nodes (that don't
  867.  * need to know whether the rest of the match failed) by a loop instead of
  868.  * by recursion.
  869.  */
  870. static int            /* 0 failure, 1 success */
  871. regmatch(prog)
  872.     char           *prog;
  873. {
  874.     register char  *scan;    /* Current node. */
  875.     char           *next;    /* Next node. */
  876.     extern char    *strchr();
  877.  
  878.     scan = prog;
  879. #ifdef DEBUG
  880.     if (scan != NULL && regnarrate)
  881.     fprintf(stderr, "%s(\n", regprop(scan));
  882. #endif
  883.     while (scan != NULL) {
  884. #ifdef DEBUG
  885.     if (regnarrate)
  886.         fprintf(stderr, "%s...\n", regprop(scan));
  887. #endif
  888.     next = regnext(scan);
  889.  
  890.     switch (OP(scan)) {
  891.       case BOL:
  892.         if (reginput != regbol)
  893.         return (0);
  894.         break;
  895.       case EOL:
  896.         if (*reginput != '\0')
  897.         return (0);
  898.         break;
  899.       case ANY:
  900.         if (*reginput == '\0')
  901.         return (0);
  902.         reginput++;
  903.         break;
  904.       case EXACTLY:{
  905.         register int    len;
  906.         register char  *opnd;
  907.  
  908.         opnd = OPERAND(scan);
  909.         /* Inline the first character, for speed. */
  910.         if (mkup(*opnd) != mkup(*reginput))
  911.             return (0);
  912.         len = strlen(opnd);
  913.         if (len > 1 && cstrncmp(opnd, reginput, len) != 0)
  914.             return (0);
  915.         reginput += len;
  916.         }
  917.         break;
  918.       case ANYOF:
  919.         if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  920.         return (0);
  921.         reginput++;
  922.         break;
  923.       case ANYBUT:
  924.         if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  925.         return (0);
  926.         reginput++;
  927.         break;
  928.       case NOTHING:
  929.         break;
  930.       case BACK:
  931.         break;
  932.       case OPEN + 1:
  933.       case OPEN + 2:
  934.       case OPEN + 3:
  935.       case OPEN + 4:
  936.       case OPEN + 5:
  937.       case OPEN + 6:
  938.       case OPEN + 7:
  939.       case OPEN + 8:
  940.       case OPEN + 9:{
  941.         register int    no;
  942.         register char  *save;
  943.  
  944.         no = OP(scan) - OPEN;
  945.         save = reginput;
  946.  
  947.         if (regmatch(next)) {
  948.             /*
  949.              * Don't set startp if some later invocation of the same
  950.              * parentheses already has. 
  951.              */
  952.             if (regstartp[no] == NULL)
  953.             regstartp[no] = save;
  954.             return (1);
  955.         } else
  956.             return (0);
  957.         }
  958.         /* break; Not Reached */
  959.       case CLOSE + 1:
  960.       case CLOSE + 2:
  961.       case CLOSE + 3:
  962.       case CLOSE + 4:
  963.       case CLOSE + 5:
  964.       case CLOSE + 6:
  965.       case CLOSE + 7:
  966.       case CLOSE + 8:
  967.       case CLOSE + 9:{
  968.         register int    no;
  969.         register char  *save;
  970.  
  971.         no = OP(scan) - CLOSE;
  972.         save = reginput;
  973.  
  974.         if (regmatch(next)) {
  975.             /*
  976.              * Don't set endp if some later invocation of the same
  977.              * parentheses already has. 
  978.              */
  979.             if (regendp[no] == NULL)
  980.             regendp[no] = save;
  981.             return (1);
  982.         } else
  983.             return (0);
  984.         }
  985.         /* break; Not Reached */
  986.       case BRANCH:{
  987.         register char  *save;
  988.  
  989.         if (OP(next) != BRANCH)    /* No choice. */
  990.             next = OPERAND(scan);    /* Avoid recursion. */
  991.         else {
  992.             do {
  993.             save = reginput;
  994.             if (regmatch(OPERAND(scan)))
  995.                 return (1);
  996.             reginput = save;
  997.             scan = regnext(scan);
  998.             } while (scan != NULL && OP(scan) == BRANCH);
  999.             return (0);
  1000.             /* NOTREACHED */
  1001.         }
  1002.         }
  1003.         break;
  1004.       case STAR:
  1005.       case PLUS:{
  1006.         register char   nextch;
  1007.         register int    no;
  1008.         register char  *save;
  1009.         register int    min;
  1010.  
  1011.         /*
  1012.          * Lookahead to avoid useless match attempts when we know
  1013.          * what character comes next. 
  1014.          */
  1015.         nextch = '\0';
  1016.         if (OP(next) == EXACTLY)
  1017.             nextch = *OPERAND(next);
  1018.         min = (OP(scan) == STAR) ? 0 : 1;
  1019.         save = reginput;
  1020.         no = regrepeat(OPERAND(scan));
  1021.         while (no >= min) {
  1022.             /* If it could work, try it. */
  1023.             if (nextch == '\0' || *reginput == nextch)
  1024.             if (regmatch(next))
  1025.                 return (1);
  1026.             /* Couldn't or didn't -- back up. */
  1027.             no--;
  1028.             reginput = save + no;
  1029.         }
  1030.         return (0);
  1031.         }
  1032.         /* break; Not Reached */
  1033.       case END:
  1034.         return (1);        /* Success! */
  1035.         /* break; Not Reached */
  1036.       default:
  1037.         regerror("memory corruption");
  1038.         return (0);
  1039.         /* break; Not Reached */
  1040.     }
  1041.  
  1042.     scan = next;
  1043.     }
  1044.  
  1045.     /*
  1046.      * We get here only if there's trouble -- normally "case END" is the
  1047.      * terminating point. 
  1048.      */
  1049.     regerror("corrupted pointers");
  1050.     return (0);
  1051. }
  1052.  
  1053. /*
  1054.  - regrepeat - repeatedly match something simple, report how many
  1055.  */
  1056. static int
  1057. regrepeat(p)
  1058.     char           *p;
  1059. {
  1060.     register int    count = 0;
  1061.     register char  *scan;
  1062.     register char  *opnd;
  1063.  
  1064.     scan = reginput;
  1065.     opnd = OPERAND(p);
  1066.     switch (OP(p)) {
  1067.       case ANY:
  1068.     count = strlen(scan);
  1069.     scan += count;
  1070.     break;
  1071.       case EXACTLY:
  1072.     while (mkup(*opnd) == mkup(*scan)) {
  1073.         count++;
  1074.         scan++;
  1075.     }
  1076.     break;
  1077.       case ANYOF:
  1078.     while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1079.         count++;
  1080.         scan++;
  1081.     }
  1082.     break;
  1083.       case ANYBUT:
  1084.     while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1085.         count++;
  1086.         scan++;
  1087.     }
  1088.     break;
  1089.       default:            /* Oh dear.  Called inappropriately. */
  1090.     regerror("internal foulup");
  1091.     count = 0;        /* Best compromise. */
  1092.     break;
  1093.     }
  1094.     reginput = scan;
  1095.  
  1096.     return (count);
  1097. }
  1098.  
  1099. /*
  1100.  - regnext - dig the "next" pointer out of a node
  1101.  */
  1102. static char    *
  1103. regnext(p)
  1104.     register char  *p;
  1105. {
  1106.     register int    offset;
  1107.  
  1108.     if (p == ®dummy)
  1109.     return (NULL);
  1110.  
  1111.     offset = NEXT(p);
  1112.     if (offset == 0)
  1113.     return (NULL);
  1114.  
  1115.     if (OP(p) == BACK)
  1116.     return (p - offset);
  1117.     else
  1118.     return (p + offset);
  1119. }
  1120.  
  1121. #ifdef DEBUG
  1122.  
  1123. STATIC char    *regprop();
  1124.  
  1125. /*
  1126.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1127.  */
  1128. void
  1129. regdump(r)
  1130.     regexp         *r;
  1131. {
  1132.     register char  *s;
  1133.     register char   op = EXACTLY;    /* Arbitrary non-END op. */
  1134.     register char  *next;
  1135.     extern char    *strchr();
  1136.  
  1137.  
  1138.     s = r->program + 1;
  1139.     while (op != END) {        /* While that wasn't END last time... */
  1140.     op = OP(s);
  1141.     printf("%2d%s", s - r->program, regprop(s));    /* Where, what. */
  1142.     next = regnext(s);
  1143.     if (next == NULL)    /* Next ptr. */
  1144.         printf("(0)");
  1145.     else
  1146.         printf("(%d)", (s - r->program) + (next - s));
  1147.     s += 3;
  1148.     if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1149.         /* Literal string, where present. */
  1150.         while (*s != '\0') {
  1151.         putchar(*s);
  1152.         s++;
  1153.         }
  1154.         s++;
  1155.     }
  1156.     putchar('\n');
  1157.     }
  1158.  
  1159.     /* Header fields of interest. */
  1160.     if (r->regstart != '\0')
  1161.     printf("start `%c' ", r->regstart);
  1162.     if (r->reganch)
  1163.     printf("anchored ");
  1164.     if (r->regmust != NULL)
  1165.     printf("must have \"%s\"", r->regmust);
  1166.     printf("\n");
  1167. }
  1168.  
  1169. /*
  1170.  - regprop - printable representation of opcode
  1171.  */
  1172. static char    *
  1173. regprop(op)
  1174.     char           *op;
  1175. {
  1176.     register char  *p;
  1177.     static char     buf[50];
  1178.  
  1179.     (void) strcpy(buf, ":");
  1180.  
  1181.     switch (OP(op)) {
  1182.       case BOL:
  1183.     p = "BOL";
  1184.     break;
  1185.       case EOL:
  1186.     p = "EOL";
  1187.     break;
  1188.       case ANY:
  1189.     p = "ANY";
  1190.     break;
  1191.       case ANYOF:
  1192.     p = "ANYOF";
  1193.     break;
  1194.       case ANYBUT:
  1195.     p = "ANYBUT";
  1196.     break;
  1197.       case BRANCH:
  1198.     p = "BRANCH";
  1199.     break;
  1200.       case EXACTLY:
  1201.     p = "EXACTLY";
  1202.     break;
  1203.       case NOTHING:
  1204.     p = "NOTHING";
  1205.     break;
  1206.       case BACK:
  1207.     p = "BACK";
  1208.     break;
  1209.       case END:
  1210.     p = "END";
  1211.     break;
  1212.       case OPEN + 1:
  1213.       case OPEN + 2:
  1214.       case OPEN + 3:
  1215.       case OPEN + 4:
  1216.       case OPEN + 5:
  1217.       case OPEN + 6:
  1218.       case OPEN + 7:
  1219.       case OPEN + 8:
  1220.       case OPEN + 9:
  1221.     sprintf(buf + strlen(buf), "OPEN%d", OP(op) - OPEN);
  1222.     p = NULL;
  1223.     break;
  1224.       case CLOSE + 1:
  1225.       case CLOSE + 2:
  1226.       case CLOSE + 3:
  1227.       case CLOSE + 4:
  1228.       case CLOSE + 5:
  1229.       case CLOSE + 6:
  1230.       case CLOSE + 7:
  1231.       case CLOSE + 8:
  1232.       case CLOSE + 9:
  1233.     sprintf(buf + strlen(buf), "CLOSE%d", OP(op) - CLOSE);
  1234.     p = NULL;
  1235.     break;
  1236.       case STAR:
  1237.     p = "STAR";
  1238.     break;
  1239.       case PLUS:
  1240.     p = "PLUS";
  1241.     break;
  1242.       default:
  1243.     regerror("corrupted opcode");
  1244.     break;
  1245.     }
  1246.     if (p != NULL)
  1247.     (void) strcat(buf, p);
  1248.     return (buf);
  1249. }
  1250. #endif
  1251.  
  1252. /*
  1253.  * The following is provided for those people who do not have strcspn() in
  1254.  * their C libraries.  They should get off their butts and do something
  1255.  * about it; at least one public-domain implementation of those (highly
  1256.  * useful) string routines has been published on Usenet.
  1257.  */
  1258. #ifdef STRCSPN
  1259. /*
  1260.  * strcspn - find length of initial segment of s1 consisting entirely
  1261.  * of characters not from s2
  1262.  */
  1263.  
  1264. static int
  1265. strcspn(s1, s2)
  1266.     char           *s1;
  1267.     char           *s2;
  1268. {
  1269.     register char  *scan1;
  1270.     register char  *scan2;
  1271.     register int    count;
  1272.  
  1273.     count = 0;
  1274.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1275.     for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1276.         if (*scan1 == *scan2++)
  1277.         return (count);
  1278.     count++;
  1279.     }
  1280.     return (count);
  1281. }
  1282. #endif
  1283.  
  1284. int
  1285. cstrncmp(s1, s2, n)
  1286.     char           *s1, *s2;
  1287.     int             n;
  1288. {
  1289.     char           *p, *S1, *S2, *strsave();
  1290.     int             rval;
  1291.  
  1292.     if (!reg_ic)
  1293.     return (strncmp(s1, s2, n));
  1294.  
  1295.     S1 = strsave(s1);
  1296.     S2 = strsave(s2);
  1297.  
  1298.     for (p = S1; *p; p++)
  1299.     if (islower(*p))
  1300.         *p = toupper(*p);
  1301.  
  1302.     for (p = S2; *p; p++)
  1303.     if (islower(*p))
  1304.         *p = toupper(*p);
  1305.  
  1306.     rval = strncmp(S1, S2, n);
  1307.  
  1308.     free(S1);
  1309.     free(S2);
  1310.  
  1311.     return rval;
  1312. }
  1313.  
  1314. char           *
  1315. cstrchr(s, c)
  1316.     char           *s;
  1317.     char            c;
  1318. {
  1319.     char           *p;
  1320.  
  1321.     for (p = s; *p; p++) {
  1322.     if (mkup(*p) == mkup(c))
  1323.         return p;
  1324.     }
  1325.     return NULL;
  1326. }
  1327. SHAR_EOF
  1328. cat << \SHAR_EOF > search.c
  1329. /*
  1330.  * STEVIE - Simply Try this Editor for VI Enthusiasts
  1331.  *
  1332.  * Code Contributions By : Tim Thompson           twitch!tjt
  1333.  *                         Tony Andrews           onecom!wldrdg!tony 
  1334.  *                         G. R. (Fred) Walter    watmath!watcgl!grwalter 
  1335.  */
  1336.  
  1337. #include "stevie.h"
  1338. /* modified Henry Spencer's regular expression routines */
  1339. #include "regexp.h"
  1340.  
  1341. #ifdef    MEGAMAX
  1342. overlay "search"
  1343. #endif
  1344.  
  1345. /*
  1346.  * This file contains various searching-related routines. These fall into
  1347.  * three groups: string searches (for /, ?, n, and N), character searches
  1348.  * within a single line (for f, F, t, T, etc), and "other" kinds of searches
  1349.  * like the '%' command, and 'word' searches. 
  1350.  */
  1351.  
  1352. /*
  1353.  * String searches 
  1354.  *
  1355.  * The actual searches are done using Henry Spencer's regular expression
  1356.  * library. 
  1357.  */
  1358.  
  1359. #define    BEGWORD    "([^a-zA-Z0-9_]|^)"    /* replaces "\<" in search strings */
  1360. #define    ENDWORD    "([^a-zA-Z0-9_]|$)"    /* likewise replaces "\>" */
  1361.  
  1362. bool_t begword;            /* does the search include a 'begin word'
  1363.                  * match */
  1364.  
  1365. /*
  1366.  * mapstring(s) - map special backslash sequences 
  1367.  */
  1368. static char    *
  1369. mapstring(s)
  1370.     register char  *s;
  1371. {
  1372.     static char     ns[MAX_COLUMNS + 1];
  1373.     register char  *p;
  1374.  
  1375.     begword = FALSE;
  1376.  
  1377.     for (p = ns; *s; s++) {
  1378.     if ((*s == '(') || (*s == ')')) {
  1379.         *p++ = '\\';
  1380.         *p++ = *s;
  1381.         continue;
  1382.     }
  1383.     if (*s != '\\') {    /* not an escape */
  1384.         *p++ = *s;
  1385.         continue;
  1386.     }
  1387.     switch (*++s) {
  1388.       case '/':
  1389.         *p++ = '/';
  1390.         break;
  1391.  
  1392.       case '<':
  1393.         strcpy(p, BEGWORD);
  1394.         p += strlen(BEGWORD);
  1395.         begword = TRUE;
  1396.         break;
  1397.  
  1398.       case '>':
  1399.         strcpy(p, ENDWORD);
  1400.         p += strlen(ENDWORD);
  1401.         break;
  1402.  
  1403.       default:
  1404.         *p++ = '\\';
  1405.         *p++ = *s;
  1406.         break;
  1407.     }
  1408.     }
  1409.     *p++ = NUL;
  1410.  
  1411.     return ns;
  1412. }
  1413.  
  1414. static LPtr    *
  1415. bcksearch(str)
  1416.     char           *str;
  1417. {
  1418.     static LPtr     infile;
  1419.     register LPtr  *p;
  1420.     regexp         *prog;
  1421.     register char  *s;
  1422.     register int    i;
  1423.     bool_t          want_start = (*str == '^');    /* looking for start of line? */
  1424.     register char  *match;
  1425.  
  1426.     /* make sure str isn't empty */
  1427.     if (str == NULL || *str == NUL)
  1428.     return NULL;
  1429.  
  1430.     if ((prog = regcomp(str)) == NULL) {
  1431.     emsg("Invalid search string");
  1432.     return NULL;
  1433.     }
  1434.     p = Curschar;
  1435.     dec(p);
  1436.  
  1437.     if (begword)        /* so we don't get stuck on one match */
  1438.     dec(p);
  1439.  
  1440.     i = (want_start) ? 0 : p->index;
  1441.  
  1442.     do {
  1443.     s = p->linep->s;
  1444.  
  1445.     if (regexec(prog, s, TRUE)) {    /* match somewhere on line */
  1446.  
  1447.         if (want_start) {    /* could only have been one */
  1448.         infile.linep = p->linep;
  1449.         infile.index = (int) (prog->startp[0] - s);
  1450.         free((char *) prog);
  1451.         return (&infile);
  1452.         }
  1453.         /*
  1454.          * Now, if there are multiple matches on this line, we have to
  1455.          * get the last one. Or the last one before the cursor, if we're
  1456.          * on that line. 
  1457.          */
  1458.  
  1459.         match = prog->startp[0];
  1460.  
  1461.         while (regexec(prog, prog->endp[0], FALSE)) {
  1462.         if ((i >= 0) && ((prog->startp[0] - s) > i))
  1463.             break;
  1464.         match = prog->startp[0];
  1465.         }
  1466.  
  1467.         if ((i >= 0) && ((match - s) > i)) {
  1468.         i = -1;
  1469.         continue;
  1470.         }
  1471.         infile.linep = p->linep;
  1472.         infile.index = (int) (match - s);
  1473.         free((char *) prog);
  1474.         return (&infile);
  1475.     }
  1476.     i = -1;
  1477.  
  1478.     } while ((p = prevline(p)) != NULL);
  1479.  
  1480.     /*
  1481.      * If wrapscan isn't set, bag the search now 
  1482.      */
  1483.     if (!P(P_WS)) {
  1484.     free((char *) prog);
  1485.     return NULL;
  1486.     }
  1487.     /* search backward from the end of the file */
  1488.     p = prevline(Fileend);
  1489.     do {
  1490.     s = p->linep->s;
  1491.  
  1492.     if (regexec(prog, s, TRUE)) {    /* match somewhere on line */
  1493.  
  1494.         if (want_start) {    /* could only have been one */
  1495.         infile.linep = p->linep;
  1496.         infile.index = (int) (prog->startp[0] - s);
  1497.         free((char *) prog);
  1498.         return (&infile);
  1499.         }
  1500.         /*
  1501.          * Now, if there are multiple matches on this line, we have to
  1502.          * get the last one. 
  1503.          */
  1504.  
  1505.         match = prog->startp[0];
  1506.  
  1507.         while (regexec(prog, prog->endp[0], FALSE))
  1508.         match = prog->startp[0];
  1509.  
  1510.         infile.linep = p->linep;
  1511.         infile.index = (int) (match - s);
  1512.         free((char *) prog);
  1513.         return (&infile);
  1514.     }
  1515.     if (p->linep == Curschar->linep)
  1516.         break;
  1517.  
  1518.     } while ((p = prevline(p)) != NULL);
  1519.  
  1520.     free((char *) prog);
  1521.     return NULL;
  1522. }
  1523.  
  1524. static LPtr    *
  1525. fwdsearch(str)
  1526.     char           *str;
  1527. {
  1528.     static LPtr     infile;
  1529.     LPtr           *p;
  1530.     regexp         *prog;
  1531.     bool_t          want_start = (*str == '^');    /* looking for start of line? */
  1532.  
  1533.     char           *s;
  1534.     int             i;
  1535.  
  1536.     if ((prog = regcomp(str)) == NULL) {
  1537.     emsg("Invalid search string");
  1538.     return NULL;
  1539.     }
  1540.     p = Curschar;
  1541.     i = Curschar->index + 1;
  1542.     do {
  1543.     s = p->linep->s + i;
  1544.     i = 0;
  1545.  
  1546.     if (regexec(prog, s, i == 0)) {    /* got a match */
  1547.         /*
  1548.          * If we wanted the start of a line and we aren't really there,
  1549.          * then a match doesn't count. 
  1550.          */
  1551.         if (want_start && (s != p->linep->s))
  1552.         continue;
  1553.  
  1554.         infile.linep = p->linep;
  1555.         infile.index = (int) (prog->startp[0] - p->linep->s);
  1556.         free((char *) prog);
  1557.         return (&infile);
  1558.     }
  1559.     } while ((p = nextline(p)) != NULL);
  1560.  
  1561.     /*
  1562.      * If wrapscan isn't set, then don't scan from the beginning of the file.
  1563.      * Just return failure here. 
  1564.      */
  1565.     if (!P(P_WS)) {
  1566.     free((char *) prog);
  1567.     return NULL;
  1568.     }
  1569.     /* search from the beginning of the file to Curschar */
  1570.     for (p = Filemem; p != NULL; p = nextline(p)) {
  1571.     s = p->linep->s;
  1572.  
  1573.     if (regexec(prog, s, TRUE)) {    /* got a match */
  1574.         infile.linep = p->linep;
  1575.         infile.index = (int) (prog->startp[0] - s);
  1576.         free((char *) prog);
  1577.         return (&infile);
  1578.     }
  1579.     if (p->linep == Curschar->linep)
  1580.         break;
  1581.     }
  1582.  
  1583.     free((char *) prog);
  1584.     return (NULL);
  1585. }
  1586.  
  1587. static char    *laststr = NULL;
  1588. static int      lastsdir;
  1589.  
  1590. static LPtr    *
  1591. ssearch(dir, str)
  1592.     int             dir;    /* FORWARD or BACKWARD */
  1593.     char           *str;
  1594. {
  1595.     LPtr           *pos;
  1596.  
  1597.     reg_ic = P(P_IC);        /* tell the regexp routines how to search */
  1598.  
  1599.     if (laststr != str) {
  1600.     if (laststr != NULL)
  1601.         free(laststr);
  1602.     laststr = strsave(str);
  1603.     }
  1604.     lastsdir = dir;
  1605.  
  1606.     if (dir == BACKWARD)
  1607.     pos = bcksearch(mapstring(str));
  1608.     else
  1609.     pos = fwdsearch(mapstring(str));
  1610.  
  1611.     /*
  1612.      * This is kind of a kludge, but its needed to make 'beginning of word'
  1613.      * searches land on the right place. 
  1614.      */
  1615.     if (pos != NULL && begword) {
  1616.     if (pos->index != 0)
  1617.         pos->index += 1;
  1618.     }
  1619.     return pos;
  1620. }
  1621.  
  1622. bool_t
  1623. dosearch(dir, str)
  1624.     int             dir;
  1625.     char           *str;
  1626. {
  1627.     LPtr           *p;
  1628.  
  1629.     if ((p = ssearch(dir, str)) == NULL) {
  1630.     msg("Pattern not found");
  1631.     return (FALSE);
  1632.     } else {
  1633.     LPtr            savep;
  1634.  
  1635.     cursupdate();
  1636.     /* if we're backing up, we make sure the line we're on */
  1637.     /* is on the screen. */
  1638.     setpcmark();
  1639.     *Curschar = savep = *p;
  1640.     cursupdate();
  1641.  
  1642.     return (TRUE);
  1643.     }
  1644. }
  1645.  
  1646. void
  1647. searchagain(dir)
  1648.     int             dir;
  1649. {
  1650.     if (laststr == NULL)
  1651.     beep();
  1652.     else
  1653.     dosearch(dir, laststr);
  1654.  
  1655.     lastsdir = dir;
  1656. }
  1657.  
  1658. #define    OTHERDIR(x)    (((x) == FORWARD) ? BACKWARD : FORWARD)
  1659.  
  1660. bool_t
  1661. repsearch(flag)
  1662.     bool_t          flag;
  1663. {
  1664.     int             dir = lastsdir;
  1665.     bool_t          found;
  1666.  
  1667.     if (laststr == NULL) {
  1668.     beep();
  1669.     return FALSE;
  1670.     }
  1671.     found = dosearch(flag ? OTHERDIR(lastsdir) : lastsdir, laststr);
  1672.  
  1673.     /*
  1674.      * We have to save and restore 'lastsdir' because it gets munged by
  1675.      * ssearch() and winds up saving the wrong direction from here if 'flag'
  1676.      * is true. 
  1677.      */
  1678.     lastsdir = dir;
  1679.  
  1680.     return (found);
  1681. }
  1682.  
  1683. /*
  1684.  * regerror - called by regexp routines when errors are detected. 
  1685.  */
  1686. void
  1687. regerror(s)
  1688.     char           *s;
  1689. {
  1690.     emsg(s);
  1691. }
  1692.  
  1693. /*
  1694.  * dosub(lp, up, cmd)
  1695.  *
  1696.  * Perform a substitution from line 'lp' to line 'up' using the
  1697.  * command pointed to by 'cmd' which should be of the form:
  1698.  *
  1699.  * /pattern/substitution/g
  1700.  *
  1701.  * The trailing 'g' is optional and, if present, indicates that multiple
  1702.  * substitutions should be performed on each line, if applicable.
  1703.  * The usual escapes are supported as described in the regexp docs.
  1704.  */
  1705.  
  1706. void
  1707. dosub(lp, up, cmd)
  1708.     LPtr           *lp, *up;
  1709.     char           *cmd;
  1710. {
  1711.     LINE           *cp;
  1712.     char           *pat, *sub;
  1713.     regexp         *prog;
  1714.     int             nsubs;
  1715.     bool_t          do_all;    /* do multiple substitutions per line */
  1716.     int             n;
  1717.  
  1718.     /*
  1719.      * If no range was given, do the current line. If only one line was
  1720.      * given, just do that one. 
  1721.      */
  1722.     if (lp->linep == NULL)
  1723.     *up = *lp = *Curschar;
  1724.     else {
  1725.     if (up->linep == NULL)
  1726.         *up = *lp;
  1727.     }
  1728.  
  1729.     pat = ++cmd;        /* skip the initial '/' */
  1730.  
  1731.     while (*cmd) {
  1732.     if (cmd[0] == '/' && cmd[-1] != '\\') {
  1733.         *cmd++ = NUL;
  1734.         break;
  1735.     }
  1736.     cmd++;
  1737.     }
  1738.  
  1739.     if (*pat == NUL) {
  1740.     emsg("NULL pattern specified");
  1741.     return;
  1742.     }
  1743.     sub = cmd;
  1744.  
  1745.     do_all = FALSE;
  1746.  
  1747.     while (*cmd) {
  1748.     if (cmd[0] == '/' && cmd[-1] != '\\') {
  1749.         do_all = (cmd[1] == 'g');
  1750.         *cmd++ = NUL;
  1751.         break;
  1752.     }
  1753.     cmd++;
  1754.     }
  1755.  
  1756.     reg_ic = P(P_IC);        /* set "ignore case" flag appropriately */
  1757.  
  1758.     if ((prog = regcomp(pat)) == NULL) {
  1759.     emsg("Invalid search string");
  1760.     return;
  1761.     }
  1762.     nsubs = 0;
  1763.  
  1764.     ResetBuffers();
  1765.     n = RowNumber(lp);
  1766.  
  1767.     cp = lp->linep;
  1768.     for (; cp != Fileend->linep && cp != NULL; cp = cp->next, n++) {
  1769.     if (regexec(prog, cp->s, TRUE)) {    /* a match on this line */
  1770.         char           *ns, *sns, *p;
  1771.  
  1772.         /*
  1773.          * Save the line that was last changed for the final cursor
  1774.          * position (just like the real vi). 
  1775.          */
  1776.         Curschar->linep = cp;
  1777.  
  1778.         /*
  1779.          * Get some space for a temporary buffer to do the substitution
  1780.          * into. 
  1781.          */
  1782.         sns = ns = alloc(2048);
  1783.         *sns = NUL;
  1784.  
  1785.         p = cp->s;
  1786.  
  1787.         do {
  1788.         for (ns = sns; *ns; ns++);
  1789.         /*
  1790.          * copy up to the part that matched 
  1791.          */
  1792.         while (p < prog->startp[0])
  1793.             *ns++ = *p++;
  1794.  
  1795.         regsub(prog, sub, ns);
  1796.  
  1797.         /*
  1798.          * continue searching after the match 
  1799.          */
  1800.         p = prog->endp[0];
  1801.  
  1802.         } while (regexec(prog, p, FALSE) && do_all);
  1803.  
  1804.         for (ns = sns; *ns; ns++);
  1805.  
  1806.         /*
  1807.          * copy the rest of the line, that didn't match 
  1808.          */
  1809.         while (*p)
  1810.         *ns++ = *p++;
  1811.  
  1812.         *ns = NUL;
  1813.  
  1814.         AppendPositionToUndoUndobuff(0, n);
  1815.         AppendPositionToUndobuff(0, n);
  1816.         AppendToUndoUndobuff("c$");
  1817.         AppendToUndobuff("c$");
  1818.         AppendToUndoUndobuff(sns);
  1819.         AppendToUndobuff(cp->s);
  1820.         AppendToUndoUndobuff(ESC_STR);
  1821.         AppendToUndobuff(ESC_STR);
  1822.  
  1823.         free(cp->s);    /* free the original line */
  1824.         cp->s = strsave(sns);    /* and save the modified str */
  1825.         cp->size = strlen(cp->s) + 1;
  1826.         free(sns);        /* free the temp buffer */
  1827.         nsubs++;
  1828.     }
  1829.     if (cp == up->linep)
  1830.         break;
  1831.     }
  1832.  
  1833.     if (nsubs) {
  1834.     CHANGED;
  1835.     AppendPositionToUndoUndobuff(0, 1);
  1836.     AppendPositionToUndobuff(0, 1);
  1837.     updateNextscreen(NOT_VALID);    /* need this to update LineSizes */
  1838.     cursupdate();
  1839.     beginline(TRUE);
  1840.     if (nsubs >= P(P_RP))
  1841.         smsg("%d substitution%c", nsubs, (nsubs > 1) ? 's' : ' ');
  1842.     } else
  1843.     msg("No match");
  1844.  
  1845.     free((char *) prog);
  1846. }
  1847.  
  1848. /*
  1849.  * doglob(cmd)
  1850.  *
  1851.  * Execute a global command of the form:
  1852.  *
  1853.  * g/pattern/X
  1854.  *
  1855.  * where 'x' is a command character, currently one of the following:
  1856.  *
  1857.  * d    Delete all matching lines
  1858.  * p    Print all matching lines
  1859.  *
  1860.  * The command character (as well as the trailing slash) is optional, and
  1861.  * is assumed to be 'p' if missing.
  1862.  */
  1863.  
  1864. void
  1865. doglob(lp, up, cmd)
  1866.     LPtr           *lp, *up;
  1867.     char           *cmd;
  1868. {
  1869.     LINE           *cp;
  1870.  
  1871.     char           *pat;
  1872.     regexp         *prog;
  1873.     int             ndone;
  1874.     char            cmdchar = NUL;    /* what to do with matching lines */
  1875.     int             nu = 0;
  1876.     int             nuu = 0;
  1877.  
  1878.     /*
  1879.      * If no range was given, do every line. If only one line was given, just
  1880.      * do that one. 
  1881.      */
  1882.     if (lp->linep == NULL) {
  1883.     *lp = *Filemem;
  1884.     *up = *Fileend;
  1885.     } else {
  1886.     if (up->linep == NULL)
  1887.         *up = *lp;
  1888.     }
  1889.  
  1890.     pat = ++cmd;        /* skip the initial '/' */
  1891.  
  1892.     while (*cmd) {
  1893.     if (cmd[0] == '/' && cmd[-1] != '\\') {
  1894.         cmdchar = cmd[1];
  1895.         *cmd++ = NUL;
  1896.         break;
  1897.     }
  1898.     cmd++;
  1899.     }
  1900.     if (cmdchar == NUL)
  1901.     cmdchar = 'p';
  1902.  
  1903.     reg_ic = P(P_IC);        /* set "ignore case" flag appropriately */
  1904.  
  1905.     if (cmdchar != 'd' && cmdchar != 'p') {
  1906.     emsg("Invalid command character");
  1907.     return;
  1908.     }
  1909.     if ((prog = regcomp(pat)) == NULL) {
  1910.     emsg("Invalid search string");
  1911.     return;
  1912.     }
  1913.     msg("");
  1914.     ndone = 0;
  1915.  
  1916.     nu = RowNumber(lp);
  1917.     if (cmdchar == 'd') {
  1918.     ResetBuffers();
  1919.     nuu = nu;
  1920.     }
  1921.     cp = lp->linep;
  1922.     for (; cp != Fileend->linep && cp != NULL; cp = cp->next, nu++) {
  1923.     if (regexec(prog, cp->s, TRUE)) {    /* a match on this line */
  1924.         Curschar->linep = cp;
  1925.         Curschar->index = 0;
  1926.  
  1927.         switch (cmdchar) {
  1928.  
  1929.           case 'd':    /* delete the line */
  1930.         AppendPositionToUndoUndobuff(0, nuu);
  1931.         AppendToUndoUndobuff("dd");
  1932.         if (buf1line() && (ndone == 0)) {
  1933.             AppendToUndobuff("a");
  1934.         } else if (buf1line()) {
  1935.             AppendToUndobuff("j");
  1936.             AppendToUndobuff("I");
  1937.         } else if (cp->next == Fileend->linep) {
  1938.             AppendPositionToUndobuff(0, nu);
  1939.             AppendToUndobuff("o");
  1940.         } else {
  1941.             AppendPositionToUndobuff(0, nu);
  1942.             AppendToUndobuff("O");
  1943.         }
  1944.         AppendToUndobuff(cp->s);
  1945.         AppendToUndobuff(ESC_STR);
  1946.  
  1947.         delline(1, FALSE);
  1948.         break;
  1949.  
  1950.           case 'p':    /* print the line */
  1951.         if (P(P_NU)) {
  1952.             sprintf(IObuff, "%6d  ", nu);
  1953.             outstr(IObuff);
  1954.         }
  1955.         prt_line(cp->s);
  1956.         outstr("\r\n");
  1957.         break;
  1958.         }
  1959.         ndone++;
  1960.     } else if (cmdchar == 'd') {
  1961.         nuu++;
  1962.     }
  1963.     if (cp == up->linep)
  1964.         break;
  1965.     }
  1966.  
  1967.     if (ndone) {
  1968.     switch (cmdchar) {
  1969.  
  1970.       case 'd':
  1971.         AppendPositionToUndobuff(0, 1);
  1972.         updateNextscreen(NOT_VALID);
  1973.         cursupdate();
  1974.         if (ndone >= P(P_RP))
  1975.         smsg("%d fewer line%c", ndone,
  1976.              (ndone > 1) ? 's' : ' ');
  1977.         break;
  1978.  
  1979.       case 'p':
  1980.         wait_return();
  1981.         break;
  1982.     }
  1983.     stuffReadbuff("^");
  1984.     } else
  1985.     msg("No match");
  1986.  
  1987.     free((char *) prog);
  1988. }
  1989.  
  1990. /*
  1991.  * Character Searches 
  1992.  */
  1993.  
  1994. static char     lastc = NUL;    /* last character searched for */
  1995. static int      lastcdir;    /* last direction of character search */
  1996. static int      lastctype;    /* last type of search ("find" or "to") */
  1997.  
  1998. /*
  1999.  * searchc(c, dir, type) 
  2000.  *
  2001.  * Search for character 'c', in direction 'dir'. If type is 0, move to the
  2002.  * position of the character, otherwise move to just before the char. 
  2003.  */
  2004. bool_t
  2005. searchc(c, dir, type)
  2006.     char            c;
  2007.     int             dir;
  2008.     int             type;
  2009. {
  2010.     LPtr            save;
  2011.  
  2012.     save = *Curschar;        /* save position in case we fail */
  2013.     lastc = c;
  2014.     lastcdir = dir;
  2015.     lastctype = type;
  2016.  
  2017.     /*
  2018.      * On 'to' searches, skip one to start with so we can repeat searches in
  2019.      * the same direction and have it work right. 
  2020.      */
  2021.     if (type)
  2022.     (dir == FORWARD) ? oneright() : oneleft();
  2023.  
  2024.     while ((dir == FORWARD) ? oneright() : oneleft()) {
  2025.     if (gchar(Curschar) == c) {
  2026.         if (type)
  2027.         (dir == FORWARD) ? oneleft() : oneright();
  2028.         return TRUE;
  2029.     }
  2030.     }
  2031.     *Curschar = save;
  2032.     return FALSE;
  2033. }
  2034.  
  2035. bool_t
  2036. crepsearch(flag)
  2037.     int             flag;
  2038. {
  2039.     int             dir = lastcdir;
  2040.     int             rval;
  2041.  
  2042.     if (lastc == NUL)
  2043.     return FALSE;
  2044.  
  2045.     rval = searchc(lastc, flag ? OTHERDIR(lastcdir) : lastcdir, lastctype);
  2046.  
  2047.     lastcdir = dir;        /* restore dir., since it may have changed */
  2048.  
  2049.     return rval;
  2050. }
  2051.  
  2052. /*
  2053.  * "Other" Searches 
  2054.  */
  2055.  
  2056. /*
  2057.  * showmatch - move the cursor to the matching paren or brace 
  2058.  */
  2059. LPtr           *
  2060. showmatch()
  2061. {
  2062.     static LPtr     pos;
  2063.     int             (*move) (), inc(), dec();
  2064.     char            initc = gchar(Curschar);    /* initial char */
  2065.     char            findc;    /* terminating char */
  2066.     char            c;
  2067.     int             count = 0;
  2068.  
  2069.     pos = *Curschar;        /* set starting point */
  2070.  
  2071.     switch (initc) {
  2072.  
  2073.       case '(':
  2074.     findc = ')';
  2075.     move = inc;
  2076.     break;
  2077.       case ')':
  2078.     findc = '(';
  2079.     move = dec;
  2080.     break;
  2081.       case '{':
  2082.     findc = '}';
  2083.     move = inc;
  2084.     break;
  2085.       case '}':
  2086.     findc = '{';
  2087.     move = dec;
  2088.     break;
  2089.       case '[':
  2090.     findc = ']';
  2091.     move = inc;
  2092.     break;
  2093.       case ']':
  2094.     findc = '[';
  2095.     move = dec;
  2096.     break;
  2097.       default:
  2098.     return (LPtr *) NULL;
  2099.     }
  2100.  
  2101.     while ((*move) (&pos) != -1) {    /* until end of file */
  2102.     c = gchar(&pos);
  2103.     if (c == initc)
  2104.         count++;
  2105.     else if (c == findc) {
  2106.         if (count == 0)
  2107.         return &pos;
  2108.         count--;
  2109.     }
  2110.     }
  2111.     return (LPtr *) NULL;    /* never found it */
  2112. }
  2113.  
  2114. /*
  2115.  * findfunc(dir) - Find the next function in direction 'dir' 
  2116.  *
  2117.  * Return TRUE if a function was found. 
  2118.  */
  2119. bool_t
  2120. findfunc(dir)
  2121.     int             dir;
  2122. {
  2123.     LPtr           *curr;
  2124.  
  2125.     curr = Curschar;
  2126.  
  2127.     do {
  2128.     curr = (dir == FORWARD) ? nextline(curr) : prevline(curr);
  2129.  
  2130.     if (curr != NULL && curr->linep->s[0] == '{') {
  2131.         setpcmark();
  2132.         *Curschar = *curr;
  2133.         return TRUE;
  2134.     }
  2135.     } while (curr != NULL);
  2136.  
  2137.     return FALSE;
  2138. }
  2139.  
  2140. /*
  2141.  * The following routines do the word searches performed by the 'w', 'W',
  2142.  * 'b', 'B', 'e', and 'E' commands. 
  2143.  */
  2144.  
  2145. /*
  2146.  * To perform these searches, characters are placed into one of three
  2147.  * classes, and transitions between classes determine word boundaries. 
  2148.  *
  2149.  * The classes are: 
  2150.  *
  2151.  * 0 - white space 1 - letters, digits, and underscore 2 - everything else 
  2152.  */
  2153.  
  2154. static int      stype;        /* type of the word motion being performed */
  2155.  
  2156. #define    C0(c)    (((c) == ' ') || ((c) == '\t') || ((c) == NUL))
  2157. #define    C1(c)    (isalpha(c) || isdigit(c) || ((c) == '_'))
  2158.  
  2159. /*
  2160.  * cls(c) - returns the class of character 'c' 
  2161.  *
  2162.  * The 'type' of the current search modifies the classes of characters if a 'W',
  2163.  * 'B', or 'E' motion is being done. In this case, chars. from class 2 are
  2164.  * reported as class 1 since only white space boundaries are of interest. 
  2165.  */
  2166. static int
  2167. cls(c)
  2168.     char            c;
  2169. {
  2170.     if (C0(c))
  2171.     return 0;
  2172.  
  2173.     if (C1(c))
  2174.     return 1;
  2175.  
  2176.     /*
  2177.      * If stype is non-zero, report these as class 1. 
  2178.      */
  2179.     return (stype == 0) ? 2 : 1;
  2180. }
  2181.  
  2182.  
  2183. /*
  2184.  * fwd_word(pos, type) - move forward one word 
  2185.  *
  2186.  * Returns the resulting position, or NULL if EOF was reached. 
  2187.  */
  2188. LPtr           *
  2189. fwd_word(p, type)
  2190.     LPtr           *p;
  2191.     int             type;
  2192. {
  2193.     static LPtr     pos;
  2194.     int             sclass = cls(gchar(p));    /* starting class */
  2195.  
  2196.     pos = *p;
  2197.  
  2198.     stype = type;
  2199.  
  2200.     /*
  2201.      * We always move at least one character. 
  2202.      */
  2203.     if (inc(&pos) == -1)
  2204.     return NULL;
  2205.  
  2206.     if (sclass != 0) {
  2207.     while (cls(gchar(&pos)) == sclass) {
  2208.         if (inc(&pos) == -1)
  2209.         return NULL;
  2210.     }
  2211.     /*
  2212.      * If we went from 1 -> 2 or 2 -> 1, return here. 
  2213.      */
  2214.     if (cls(gchar(&pos)) != 0)
  2215.         return &pos;
  2216.     }
  2217.     /* We're in white space; go to next non-white */
  2218.  
  2219.     while (cls(gchar(&pos)) == 0) {
  2220.     /*
  2221.      * We'll stop if we land on a blank line 
  2222.      */
  2223.     if (pos.index == 0 && pos.linep->s[0] == NUL)
  2224.         break;
  2225.  
  2226.     if (inc(&pos) == -1)
  2227.         return NULL;
  2228.     }
  2229.  
  2230.     return &pos;
  2231. }
  2232.  
  2233. /*
  2234.  * bck_word(pos, type) - move backward one word 
  2235.  *
  2236.  * Returns the resulting position, or NULL if top-of-file was reached. 
  2237.  */
  2238. LPtr           *
  2239. bck_word(p, type)
  2240.     LPtr           *p;
  2241.     int             type;
  2242. {
  2243.     static LPtr     pos;
  2244.     int             sclass = cls(gchar(p));    /* starting class */
  2245.  
  2246.     pos = *p;
  2247.  
  2248.     stype = type;
  2249.  
  2250.     if (dec(&pos) == -1)
  2251.     return NULL;
  2252.  
  2253.     /*
  2254.      * If we're in the middle of a word, we just have to back up to the start
  2255.      * of it. 
  2256.      */
  2257.     if (cls(gchar(&pos)) == sclass && sclass != 0) {
  2258.     /*
  2259.      * Move backward to start of the current word 
  2260.      */
  2261.     while (cls(gchar(&pos)) == sclass) {
  2262.         if (dec(&pos) == -1)
  2263.         return NULL;
  2264.     }
  2265.     inc(&pos);        /* overshot - forward one */
  2266.     return &pos;
  2267.     }
  2268.     /*
  2269.      * We were at the start of a word. Go back to the start of the prior
  2270.      * word. 
  2271.      */
  2272.  
  2273.     while (cls(gchar(&pos)) == 0) {    /* skip any white space */
  2274.     /*
  2275.      * We'll stop if we land on a blank line 
  2276.      */
  2277.     if (pos.index == 0 && pos.linep->s[0] == NUL)
  2278.         return &pos;
  2279.  
  2280.     if (dec(&pos) == -1)
  2281.         return NULL;
  2282.     }
  2283.  
  2284.     sclass = cls(gchar(&pos));
  2285.  
  2286.     /*
  2287.      * Move backward to start of this word. 
  2288.      */
  2289.     while (cls(gchar(&pos)) == sclass) {
  2290.     if (dec(&pos) == -1)
  2291.         return NULL;
  2292.     }
  2293.     inc(&pos);            /* overshot - forward one */
  2294.  
  2295.     return &pos;
  2296. }
  2297.  
  2298. /*
  2299.  * end_word(pos, type) - move to the end of the word 
  2300.  *
  2301.  * There is an apparent bug in the 'e' motion of the real vi. At least on the
  2302.  * System V Release 3 version for the 80386. Unlike 'b' and 'w', the 'e'
  2303.  * motion crosses blank lines. When the real vi crosses a blank line in an
  2304.  * 'e' motion, the cursor is placed on the FIRST character of the next
  2305.  * non-blank line. The 'E' command, however, works correctly. Since this
  2306.  * appears to be a bug, I have not duplicated it here. 
  2307.  *
  2308.  * Returns the resulting position, or NULL if EOF was reached. 
  2309.  */
  2310. LPtr           *
  2311. end_word(p, type)
  2312.     LPtr           *p;
  2313.     int             type;
  2314. {
  2315.     static LPtr     pos;
  2316.     int             sclass = cls(gchar(p));    /* starting class */
  2317.  
  2318.     pos = *p;
  2319.  
  2320.     stype = type;
  2321.  
  2322.     if (inc(&pos) == -1)
  2323.     return NULL;
  2324.  
  2325.     /*
  2326.      * If we're in the middle of a word, we just have to move to the end of
  2327.      * it. 
  2328.      */
  2329.     if (cls(gchar(&pos)) == sclass && sclass != 0) {
  2330.     /*
  2331.      * Move forward to end of the current word 
  2332.      */
  2333.     while (cls(gchar(&pos)) == sclass) {
  2334.         if (inc(&pos) == -1)
  2335.         return NULL;
  2336.     }
  2337.     dec(&pos);        /* overshot - forward one */
  2338.     return &pos;
  2339.     }
  2340.     /*
  2341.      * We were at the end of a word. Go to the end of the next word. 
  2342.      */
  2343.  
  2344.     while (cls(gchar(&pos)) == 0) {    /* skip any white space */
  2345.     if (inc(&pos) == -1)
  2346.         return NULL;
  2347.     }
  2348.  
  2349.     sclass = cls(gchar(&pos));
  2350.  
  2351.     /*
  2352.      * Move forward to end of this word. 
  2353.      */
  2354.     while (cls(gchar(&pos)) == sclass) {
  2355.     if (inc(&pos) == -1)
  2356.         return NULL;
  2357.     }
  2358.     dec(&pos);            /* overshot - forward one */
  2359.  
  2360.     return &pos;
  2361. }
  2362. SHAR_EOF
  2363. #    End of shell archive
  2364. exit 0
  2365. -- 
  2366. Bob Page, U of Lowell CS Dept.  page@swan.ulowell.edu  ulowell!page
  2367. Have five nice days.
  2368.